#!/usr/bin/perl
use strict;

#my ($ITER, $RANGE) = (2000000, 10000);
#my ($ITER, $RANGE) = (20000, 150);
my ($ITER, $RANGE) = (200, 15);

sub generate_ids($\@\%)
{
	my ($file_name, $results, $IDs) = @_;
	print STDERR "\tPrint $file_name...\n";
	open RESULTS, ">$file_name";
#	print RESULTS "seq1\tseq2\tasfas\n----\t----\t---\n";

	
	my $cnt_results = 0;
	# make sure first line matches
	++$cnt_results;
	my $id1 =  0;
	my $id2 =  2;
	print RESULTS "id_$id1\tid_$id2\tlong line of stuff\n";
	my ($id_a, $id_b) = ($id1, $id2);
	push(@$results,  ["id_$id_a\tid_$id_b", "id_$id1\tid_$id2\tlong line of stuff\n"]);
	$IDs->{"id_$id_a\tid_$id_b"}++;
	for (0..$ITER)
	{
		++$cnt_results;
		my $id1 =  int(rand($RANGE));
		my $id2 =  int(rand($RANGE));
		print RESULTS "id_$id1\tid_$id2\tlong line of stuff\n";
		my ($id_a, $id_b) = ($id1, $id2);
		push(@$results,  ["id_$id_a\tid_$id_b", "id_$id1\tid_$id2\tlong line of stuff\n"]);
		$IDs->{"id_$id_a\tid_$id_b"}++;
	}
	
}

my (%IDs1, %IDs2, @results1, @results2);
generate_ids("results.1.test", @results1, %IDs1);
generate_ids("results.2.test", @results2, %IDs2);
my %IDs;
for (keys %IDs1)
{
	$IDs{$_} = 1;
}
for (keys %IDs2)
{
	$IDs{$_} += 2;
}

{
	open (FILE1_FULL, 	">file1_only.ids.test") or die; 
	open (FILE2_FULL, 	">file2_only.ids.test") or die; 
	open (MERGE_FULL, 	">merged.ids.test") or die;     
	open (SHARE_FULL, 	">shared.ids.test") or die;     
	for (@results1, @results2)
	{
		my ($id, $results) = @$_;
		next unless ($IDs{$id});
		if ($IDs{$id} == 1)
		{
			print FILE1_FULL "$results";
		}
		elsif ($IDs{$id} == 2)
		{
			print FILE2_FULL "$results";
		}
		elsif ($IDs{$id} == 3)
		{
			print SHARE_FULL "$results";
		}
		print MERGE_FULL "$results";
		$IDs{$id} = 0;
	}
}


my @files = (	
				"file1_only.ids"    ,
				"file2_only.ids"    ,
				"merged.ids"        ,
				"shared.ids"        ,);
				


print STDERR "\tRunning seq_pairs_matching...\n";
system("diff_sets -x results.1.test -y results.2.test --debug");
print STDERR "\tComparing results...\n";
for my $file(@files)
{
	my @diff = `diff $file $file.test`;
	if (@diff != 0)
	{
		print STDERR "FAILED: $file $file.test are not the same!\n";
		exit;
	}
}
print STDERR "\tCleaning up...\n";
unlink (glob("*.test"));
unlink (glob("*.ids"));
print STDERR "\n\tSUCCESS!!!\n\n";

